﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DDD.EFCore.Shared
{
    public class CommandUnitOfWorkBehavior<TCommand, TResponse>//(IUnitOfWork unitOfWork) (EFContext context)
        : IPipelineBehavior<TCommand, TResponse>
        //where TContext : DbContext
        where TCommand : notnull
    {
        public virtual async Task<TResponse> Handle(TCommand request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
        {
            throw new NotImplementedException();
            //    {
            //        var response = await next();
            //        //var dbContext =  serviceProvider.GetRequierdService<TContext>();
            //        //await dbContext.SaveUnitOfWorkAsync(cancellationToken);
            //        await unitOfWork.SaveUnitOfWorkAsync(cancellationToken);
            //        return response;
            //    }
            //    // TODO: 这里没想明白 为啥自己开事务？回头再看
            //    var cmdType = typeof(TCommand);
            //    var commandName = cmdType.FullName ?? cmdType.Name;
            //    Guid id = Guid.NewGuid();
            //    if (unitOfWork.CurrentTransaction != null)
            //    {
            //        try
            //        {
            //            var response = await next();
            //            await unitOfWork.SaveUnitOfWorkAsync(cancellationToken);
            //            return response;
            //        }
            //        catch (Exception e)
            //        {
            //            throw;
            //        }
            //    }


            //    await using var transaction = unitOfWork.BeginTransaction();
            //    try
            //    {
            //        var response = await next();
            //        await unitOfWork.SaveUnitOfWorkAsync(cancellationToken);
            //        await unitOfWork.CommitAsync(cancellationToken);
            //        return response;
            //    }
            //    catch (Exception e)
            //    {
            //        await unitOfWork.RollbackAsync(cancellationToken);
            //        throw;
            //    }
            //}
        }
    }
}